import { defineStore } from "pinia";
import { getOrderListAPI, cancelOrderAPI } from "@/apis/order";
import { STATUS_MAP, ORDER_STATUS } from "@/utils/constant";

export const useOrderStore = defineStore("order", {
  state: () => ({
    orderList: [],
    currentTab: "all",
    page: 1,
    loadMoreStatus: "more",
    total: 0,
  }),

  actions: {
    // 设置订单列表
    setOrderList(list) {
      this.orderList = list;
    },

    // 添加更多订单
    appendOrderList(list) {
      this.orderList = [...this.orderList, ...list];
    },

    // 设置当前标签
    setCurrentTab(tab) {
      this.currentTab = tab;
      this.page = 1; // 重置页码
    },

    // 获取状态列表
    getStatusList() {
      switch (this.currentTab) {
        case "all":
          return [];
        case "pending":
          return Object.entries(STATUS_MAP)
            .filter(([_, value]) => value === ORDER_STATUS.PENDING_PAYMENT)
            .map(([key]) => Number(key));
        case "paid":
          return Object.entries(STATUS_MAP)
            .filter(([_, value]) => value === ORDER_STATUS.PAID)
            .map(([key]) => Number(key));
        case "afterSale":
          return [7, 8, 9, 10, 11];
        case "mall":
          return [];
        default:
          return [];
      }
    },

    // 获取订单列表
    async fetchOrders(isLoadMore = false) {
      this.loadMoreStatus = "loading";
      try {
        const params = this.getRequestParams();
        const res = await getOrderListAPI(params);

        if (!isLoadMore) {
          this.setOrderList(res.data.list);
        } else {
          this.appendOrderList(res.data.list);
        }

        this.total = res.data.total;
        this.loadMoreStatus =
          this.orderList.length >= res.data.total ? "noMore" : "more";
      } catch (error) {
        console.error("获取订单列表失败", error);
        this.loadMoreStatus = "more";
      }
    },

    // 取消订单
    async cancelOrder(orderCode, pageType = "list") {
      uni.showModal({
        title: "提示",
        content: "确定要取消该订单吗？",
        success: async (res) => {
          if (res.confirm) {
            console.log("用户点击确定，取消订单", orderCode);
            const res = await cancelOrderAPI({ orderCode });
            if (res.code === "200") {
              uni.showToast({
                title: "取消订单成功",
              });

              if (pageType === "detail") {
                console.log("返回上一级");
                uni.navigateBack(1);
              } else {
                this.refreshOrders();
              }
            }
          }
        },
      });
    },

    // 获取请求参数
    getRequestParams() {
      const params = {
        page: this.page,
        limit: 10,
        year: "2025",
        statusList: this.getStatusList(),
      };

      // 如果是商城tab，添加type参数
      if (this.currentTab === "mall") {
        params.type = 1;
      }

      return params;
    },

    // 加载更多
    async loadMore() {
      if (this.loadMoreStatus === "loading" || this.loadMoreStatus === "noMore")
        return;
      this.page++;
      await this.fetchOrders(true);
    },

    // 刷新订单列表
    async refreshOrders() {
      this.page = 1;
      await this.fetchOrders();
    },
  },
});
